Create Trigger [dbo].[UpdateItem] ON [dbo].[InvoiceNo]
For Update As
BEGIN
	Declare @SQ as int, @PQ as int, @DQ As int, @DID int,@IID int
	Select @SQ=Qty From inserted
	Select @SQ=Qty From Deleted
	Select @SQ=Qty From Products
	Where Code =(Select Code From Inserted)
	
	Select @DID=Code From Deleted
	Select @IID=Code From Inserted
If @DID=@IID
		Begin 
			if @SQ<=@PQ+@DQ
				Begin
					Update tbl_Products Set Qty = Qty + @DQ -@SQ
					Where Code =(Select Code From Inserted)
				End
			End
	Else
		Begin
			if @SQ <= @PQ
				Begin
					Update tbl_Products Set Qty =Qty +@DQ
					Where Code=(Select Code From Deleted)
					Update tbl_Products Set Qty = Qty -@SQ
					Where Code = (Select Code From Inserted)
				End
			Else
				Begin
					Raiserror ('Qty in Stock < Qty Sold ',16,1)
					Rollback TRansaction
				End
			End
		End		
					
		